package com.xiyang.common.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.ToString;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

/**
 * 注意不可用lombok注解  他会重写hashcode和equals
 * @author xiyang.ycj
 * @since Dec 30, 2019 11:45:55 AM
 */
@DynamicInsert
@DynamicUpdate
@Entity
@Table(name = "dev_user")
@org.hibernate.annotations.Table(appliesTo = "dev_user", comment = "用户表")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    @Column(name = "nickname", columnDefinition = "varchar(50) comment'昵称'")
    private String nickname;
    @Column(name = "account", columnDefinition = "varchar(50) comment'账号'")
    private String account;
    @Column(name = "password", columnDefinition = "varchar(255) comment'登陆密码'")
    private String password;
    /**
     * 用户角色关联
     * 一个用户可以有多个角色，所以以中间表形式显示
     * joinColumns写的都是本表在中间表的外键名称， inverseJoinColumns写的是另一个表在中间表的外键名称。
     */
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "dev_user_role", joinColumns = {@JoinColumn(name = "user_id")}, inverseJoinColumns = {
            @JoinColumn(name = "role_id")})
    @JsonIgnore
    private Set<Role> roles;

    @Transient
    private Set<String> roleNames;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }


    public Set<String> getRoleNames() {
        if(roleNames==null){
            roleNames=new HashSet<>();
            for (Role role : roles) {
                this.roleNames.add(role.getRoleName());
            }
        }
        return roleNames;
    }

}
